package com.idbk.chargestation.activity.user;


import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.adapter.CommonTabAdapter;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.app.MyVersion;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonMywalletRecord;
import com.idbk.chargestation.bean.JsonMywalletRecordList;
import com.idbk.chargestation.fragment.FragmentMyWallet;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.wxapi.WXPayEntryActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的钱包
 *
 * @author zhx
 */

public class ActivityMyWallet extends BaseActivity implements OnClickListener {

    private final static String TAG = ActivityMyWallet.class.getSimpleName();
    public final static String RECORD_TYPE = "record_type";
    private Context mContext;
    private TextView mBalance;
    private ProgressDialog mDialog;
    private StringRequest mRequest;

    private RelativeLayout mRelativeCharge;
    private int userRole;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_wallet);

        mContext = ActivityMyWallet.this;

        setupView();

        setupData();

        setupTabs();
    }

    private void setupView() {
        userRole = AppContext.getInstance().getUserRole();
        setupToolBar2();//显示标题栏
        mBalance = (TextView) findViewById(R.id.activity_mywallet_balance);
        findViewById(R.id.textview_paycheck).setOnClickListener(this);

        mRelativeCharge = (RelativeLayout) findViewById(R.id.relative_charge);
        if (userRole == 2){
            mRelativeCharge.setVisibility(View.GONE);
        }else {
            mRelativeCharge.setVisibility(View.VISIBLE);
        }
    }

    private void setupData() {
        AppContext appContext = AppContext.getInstance();
        super.onResume();
        if (appContext.isLogin()) {    //判断是否已登录
            loadData();

        } else {
            Intent intent = new Intent(mContext, ActivityLogin.class);
            startActivityForResult(intent, Const.CODE_REQUEST_LOGIN);
        }
    }

    //初始化选项卡
    private void setupTabs() {
        TabLayout mTabLayout = (TabLayout) findViewById(R.id.tablayout);

        userRole = AppContext.getInstance().getUserRole();
        if (userRole == 2) {
            mTabLayout.setVisibility(View.GONE);
        }else {
            mTabLayout.setVisibility(View.VISIBLE);
        }

        if (mTabLayout != null) {
            //设置TabLayout的模式
            mTabLayout.setTabMode(TabLayout.MODE_FIXED);
            //为TabLayout添加tab名称
            mTabLayout.addTab(mTabLayout.newTab().setText("全部"));
            mTabLayout.addTab(mTabLayout.newTab().setText("消费记录"));
            mTabLayout.addTab(mTabLayout.newTab().setText("充值记录"));


            CommonTabAdapter mAdapter = new CommonTabAdapter(getSupportFragmentManager(),
                    new String[]{"全部", "消费记录", "充值记录"}, getFragmentList());
            //ViewPager加载Adapter
            ViewPager mViewPager = (ViewPager) findViewById(R.id.vp_FindFragment_pager);
            if (mViewPager != null) {
                mViewPager.setAdapter(mAdapter);
                //TabLayout加载viewpager
                mTabLayout.setupWithViewPager(mViewPager);
                mViewPager.setOffscreenPageLimit(2);
            }
        }
    }

    private List<Fragment> getFragmentList() {
        List<Fragment> fragmentList = new ArrayList<Fragment>();
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        FragmentMyWallet fragmentAll = new FragmentMyWallet();
        FragmentMyWallet fragmentConsume = new FragmentMyWallet();
        FragmentMyWallet fragmentRecharge = new FragmentMyWallet();

        Bundle bundle1 = new Bundle();
        bundle1.putInt(RECORD_TYPE, JsonMywalletRecord.RECORD_TYPE_ALL);
        Bundle bundle2 = new Bundle();
        bundle2.putInt(RECORD_TYPE, JsonMywalletRecord.RECORD_TYPE_CONSUME);
        Bundle bundle3 = new Bundle();
        bundle3.putInt(RECORD_TYPE, JsonMywalletRecord.RECORD_TYPE_RECHARGE);

        fragmentAll.setArguments(bundle1);
        fragmentConsume.setArguments(bundle2);
        fragmentRecharge.setArguments(bundle3);

        userRole = AppContext.getInstance().getUserRole();
        if (userRole == 2){
            fragmentList.add(fragmentConsume);
        }else {
            fragmentList.add(fragmentAll);
            fragmentList.add(fragmentConsume);
            fragmentList.add(fragmentRecharge);
        }

        transaction.commit();
        return fragmentList;
    }

    @Override
    protected void onRestart() {
        if (AppContext.getInstance().isLogin()) {
            ChargeStationAPI.getWalletRecord(1, 1, 0, mResponse);
        }
        super.onRestart();
    }

    private void loadData() {
        mDialog = ProgressDialog.show(mContext, null, "加载中...", true, true,
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {

                        if (mRequest != null) {
                            mRequest.cancel();
                            finish();
                        }

                    }
                });
        mRequest = ChargeStationAPI.getWalletRecord(1, 1, 0, mResponse);
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonMywalletRecordList result = GsonUtils.toBean(JsonMywalletRecordList.class, response);
            if (handleResponseStatus(result)) {
                String money = "￥" + String.valueOf(result.balance);
                mBalance.setText(money);//余额显示
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Toast.makeText(mContext,
                    R.string.common_tip_resultfail,
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            mDialog.dismiss();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Const.CODE_REQUEST_LOGIN &&
                resultCode == Const.CODE_RESPONSE_LOGIN_SUCCESS) {
            loadData();

        } else if (requestCode == Const.CODE_REQUEST_RECHARGE) {
            Log.d(TAG, "onActivityResult: requestCode : " + Const.CODE_REQUEST_RECHARGE);

        } else {
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview_paycheck:
                String version = MyVersion.getVersion(mContext);
                Intent intent;
                switch (version) {
                    case MyVersion.VERSION_ZNYD :
                       intent = new Intent(ActivityMyWallet.this, WXPayEntryActivity.class);
                        break;
                    case MyVersion.VERSION_NJYX:
                       intent = new Intent(ActivityMyWallet.this, com.yexiang.chargestation.wxapi.WXPayEntryActivity.class);
                        break;
                    default:
                        intent = new Intent(ActivityMyWallet.this, WXPayEntryActivity.class);
                        break;
                }
                startActivityForResult(intent, Const.CODE_REQUEST_RECHARGE);
                break;
            default:
                break;
        }
    }

}

